import axois from 'axios'
import { useUserStore } from '@/stores/user'
import { ElLoading, ElMessage } from 'element-plus'
// vite中配置了按需自动引入后，需要手动引入样式ElLoading才生效
import 'element-plus/theme-chalk/el-loading.css'
import { isNotEmpty } from '@/utils'
class Request {
  constructor(config) {
    // 创建axois实例
    this.instance = axois.create(config)
    // 是否显示loading 默认true
    this.showLoading = true
    // 加载实例
    this.loadingInstance = null

    // 请求拦截
    this.instance.interceptors.request.use(
      (config) => {
        if ('showLoading' in config) {
          this.showLoading = config.showLoading
        } else {
          this.showLoading = true
        }

        if (this.showLoading) {
          this.loadingInstance = ElLoading.service({
            lock: true,
            text: config.loadingText || '加载中',
            background: 'rgba(0, 0, 0, 0.7)'
          })
        }

        const userStore = useUserStore()
        const userInfo = userStore.userInfo
        if (isNotEmpty(userInfo)) {
          const token = userInfo.token
          if (isNotEmpty(token)) {
            config.headers['token'] = token
          }
        }

        return config
      },
      (error) => Promise.reject(error)
    )

    // 响应拦截
    this.instance.interceptors.response.use(
      (config) => {
        this.loadingInstance?.close()
        return config
      },
      (error) => {
        this.loadingInstance?.close()
        return Promise.reject(error)
      }
    )
  }

  request(config) {
    return new Promise((resove) => {
      this.instance
        .request(config)
        .then((res) => {
          resove(res.data)
        })
        .catch((error) => {
          ElMessage({
            type: 'error',
            message: error.message
          })
        })
    })
  }

  get(config) {
    return this.request({ ...config, method: 'GET' })
  }
  post(config) {
    return this.request({ ...config, method: 'POST' })
  }
  put(config) {
    return this.request({ ...config, method: 'PUT' })
  }
  delete(config) {
    return this.request({ ...config, method: 'DELETE' })
  }
}

const request = new Request({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 60 * 3 * 1000,
  withCredentials: true //携带cookie
})

export { request }
